package com.modulemanager.services

import android.content.Context
import com.libbase.utils.FileUtils
import com.libbase.utils.JsonUtils
import com.libbase.utils.genericType
import com.libnetwork.httpservice.HttpService
import com.libnetwork.models.apiresult.APIResult
import com.libui.BaseApplication
import com.modulemanager.ModuleManager
import io.reactivex.rxjava3.core.Single
import retrofit2.mock.BehaviorDelegate
import java.lang.reflect.Type

class MockModuleService(private val delegate: BehaviorDelegate<ModuleService>) : ModuleService {
    override fun pageValue(
        moduleType: String,
        moduleId: String?,
        pageType: String,
        pageId: String?
    ): Single<APIResult<Map<String, Any>>> {
        val jsonPath =
            ModuleManager.instance.dataSource?.jsonPath ?: return delegate.returningResponse(
                APIResult<Map<String, Any>>(200, null, null)
            )
                .pageValue(moduleType, moduleId, pageType, pageId)

        val parameters: MutableList<String> = mutableListOf()

        if (moduleId != null) {
            parameters.add(moduleId)
        }

        if (pageId != null) {
            parameters.add(pageId)
        }

        if (parameters.isEmpty()) {
            return delegate.returningResponse(APIResult<Map<String, Any>>(200, null, null))
                .pageValue(moduleType, moduleId, pageType, pageId)
        }

        val context: Context = BaseApplication.instance
            ?: return delegate.returningResponse(APIResult<Map<String, Any>>(200, null, null))
                .pageValue(moduleType, moduleId, pageType, pageId)

        val resultStr: String = FileUtils.instance.readAssetFile(
            "${jsonPath}/${
                parameters.joinToString(
                    "_",
                    "",
                    ".json"
                )
            }",
            context
        ) ?: return delegate.returningResponse(APIResult<Map<String, Any>>(200, null, null))
            .pageValue(moduleType, moduleId, pageType, pageId)

        val type: Type = genericType<APIResult<Map<String, Any>>>()
        val result: APIResult<Map<String, Any>> = JsonUtils.json.fromJson(resultStr, type)

        return delegate.returningResponse(result).pageValue(moduleType, moduleId, pageType, pageId)
    }
}

object MockModuleAPI :
    ModuleService by MockModuleService(HttpService.instance.mockRetrofit.create(ModuleService::class.java))